package org.yunshang.beltbody.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.yunshang.common.core.constant.UserConstants;
import org.yunshang.common.core.utils.MapstructUtils;
import org.yunshang.common.core.utils.StreamUtils;
import org.yunshang.common.core.utils.StringUtils;
import org.yunshang.common.excel.utils.ImageUtil;
import org.yunshang.common.mybatis.core.page.TableDataInfo;
import org.yunshang.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.yunshang.beltbody.domain.bo.TBeltBodyBo;
import org.yunshang.beltbody.domain.vo.TBeltBodyVo;
import org.yunshang.beltbody.domain.TBeltBody;
import org.yunshang.beltbody.mapper.TBeltBodyMapper;
import org.yunshang.beltbody.service.ITBeltBodyService;
import org.yunshang.common.mybatis.helper.DataBaseHelper;
import org.yunshang.customer.domain.vo.TCustomerVo;
import org.yunshang.style.domain.TStyle;
import org.yunshang.style.mapper.TStyleMapper;
import org.yunshang.system.domain.SysDept;
import org.yunshang.system.domain.SysUser;
import org.yunshang.system.domain.bo.SysUserBo;
import org.yunshang.system.domain.vo.SysOssVo;
import org.yunshang.system.domain.vo.SysUserVo;
import org.yunshang.system.mapper.SysOssMapper;
import org.yunshang.system.service.ISysOssService;

import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 带身信息Service业务层处理
 *
 * @author Lion Li
 * @date 2024-03-30
 */
@RequiredArgsConstructor
@Service
public class TBeltBodyServiceImpl implements ITBeltBodyService {

    private final TBeltBodyMapper baseMapper;

    private final ISysOssService sysOssService;

    private final SysOssMapper sysOssMapper;
    /**
     * 查询带身信息
     */
    @Override
    public TBeltBodyVo queryById(Long id){
        TBeltBodyVo beltBodeBO = baseMapper.selectVoById(id);
        getImgStr(beltBodeBO);
        return beltBodeBO;
    }

    /**
     * 获取 图片字符串
     * @param beltBodeBO
     * @return
     */
    private TBeltBodyVo getImgStr(TBeltBodyVo beltBodeBO) {
        Optional.ofNullable(beltBodeBO).ifPresent(e->{
            Optional.ofNullable(e.getImg()).ifPresent(i->{
                List<Long> ossIds = Arrays.asList(e.getImg().split(",")).stream().map(x-> Long.valueOf(x)).collect(Collectors.toList());
                List<SysOssVo> ossList = sysOssService.listByIds(ossIds);
                Map<Long, String> map = ossList.stream().collect(Collectors.toMap(o-> o.getOssId(), o-> o.getUrl()));
                e.setImgMap(map);
            });
        });
        return beltBodeBO;

    }

    /**
     * 查询带身信息列表
     */
    @Override
    public TableDataInfo<TBeltBodyVo> queryPageList(TBeltBodyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TBeltBody> lqw = buildQueryWrapper(bo);
        Page<TBeltBodyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<TBeltBodyVo> voList = result.getRecords().stream().map(v-> getImgStr(v)).collect(Collectors.toList());
        result.setRecords(voList);
        return TableDataInfo.build(result);
    }

    /**
     * 查询带身信息列表
     */
    @Override
    public List<TBeltBodyVo> queryList(TBeltBodyBo bo) {
        Wrapper<TBeltBody> lqw = buildQueryWrappers(bo);
        //List<TBeltBodyVo> list = baseMapper.selectVoList(lqw);
        List<TBeltBodyVo> list = baseMapper.selectBeltBodyList(lqw);
        list.stream().forEach(e->{
            getLogUrl(e);

        });
        return list;
    }

    public TBeltBodyVo getLogUrl(TBeltBodyVo beltBodyVo){
        List<URL> urlList = new ArrayList<>();
        Optional.ofNullable(beltBodyVo.getImg()).ifPresent(d->
            {
                Arrays.asList(d.split(",")).forEach(e-> {
                    SysOssVo ossVo = sysOssMapper.selectVoById(e);
                    Optional<SysOssVo> optional = Optional.ofNullable(ossVo);
                    if (optional.isPresent()) {
                        beltBodyVo.setLogUrl(optional.get().getUrl());
                        try {
                            URL url = ImageUtil.downloadAndCompress(optional.get().getUrl(),0.1f);
                            urlList.add(url);
                        }catch (Exception ez){
                            ez.printStackTrace();
                        }
                    }
                });


            }
        );
        beltBodyVo.setLogWebUrl(urlList);
        return beltBodyVo;
    }

    private LambdaQueryWrapper<TBeltBody> buildQueryWrapper(TBeltBodyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TBeltBody> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getWidth()), TBeltBody::getWidth, bo.getWidth());
        lqw.like(StringUtils.isNotBlank(bo.getThickness()), TBeltBody::getThickness, bo.getThickness());
        lqw.eq(bo.getType() != null, TBeltBody::getType, bo.getType());
        lqw.eq(bo.getMianpi() != null, TBeltBody::getMianpi, bo.getMianpi());
        lqw.eq(bo.getMpColor() != null, TBeltBody::getMpColor, bo.getMpColor());
        lqw.like(StringUtils.isNotBlank(bo.getMpCaizhi()), TBeltBody::getMpCaizhi, bo.getMpCaizhi());
        lqw.eq(bo.getDipi() != null, TBeltBody::getDipi, bo.getDipi());
        lqw.eq(bo.getDpColor() != null, TBeltBody::getDpColor, bo.getDpColor());
        lqw.like(StringUtils.isNotBlank(bo.getDpCaizhi()), TBeltBody::getDpCaizhi, bo.getDpCaizhi());
        lqw.eq(StringUtils.isNotBlank(bo.getTailType()), TBeltBody::getTailType, bo.getTailType());
        lqw.like(bo.getCostPrice() != null, TBeltBody::getCostPrice, bo.getCostPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TBeltBody::getStatus, bo.getStatus());
        return lqw;
    }


    private Wrapper<TBeltBody> buildQueryWrappers(TBeltBodyBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<TBeltBody> wrapper = Wrappers.query();
        wrapper.like(StringUtils.isNotBlank(bo.getWidth()), "t.width", bo.getWidth())
            .like(StringUtils.isNotBlank(bo.getThickness()), "t.thickness", bo.getThickness())
            .eq(bo.getType() != null, "t.type", bo.getType())
            .eq(bo.getMianpi() != null, "t.mianpi", bo.getMianpi())
            .eq(bo.getMpColor() != null, "t.mp_color", bo.getMpColor())
            .like(StringUtils.isNotBlank(bo.getMpCaizhi()), "t.mp_caizhi", bo.getMpCaizhi())
            .eq(bo.getDipi() != null, "t.dipi", bo.getDipi())
            .eq(bo.getDpColor() != null, "t.dp_color", bo.getDpColor())
            .like(StringUtils.isNotBlank(bo.getDpCaizhi()), "t.dp_caizhi", bo.getDpCaizhi())
            .eq(StringUtils.isNotBlank(bo.getTailType()), "t.tail_type", bo.getTailType())
            .like(bo.getCostPrice() != null, "t.cost_price", bo.getCostPrice())
            .eq(StringUtils.isNotBlank(bo.getStatus()), "t.status", bo.getStatus())
            .orderByDesc("t.create_time");
        return wrapper;
    }


    /**
     * 新增带身信息
     */
    @Override
    public Boolean insertByBo(TBeltBodyBo bo) {
        TBeltBody add = MapstructUtils.convert(bo, TBeltBody.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改带身信息
     */
    @Override
    public Boolean updateByBo(TBeltBodyBo bo) {
        TBeltBody update = MapstructUtils.convert(bo, TBeltBody.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TBeltBody entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除带身信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
